package com.msi.manning.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.client.ResponseHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.msi.manning.network.data.HTTPRequestHelper;

/**


 * 
 */
public class NutritionMe extends Activity {

	public static final int MAIN_ID = Menu.FIRST;
	
    private static final String CLASSTAG = NutritionMe.class.getSimpleName();
    
    protected static final int SELECTED_CHOICE = 0;

    private EditText param1Value;
    private Button go;
    private TextView output;
    private ListView choices;
    protected ArrayList<String> result = new ArrayList<String>(); 

    private ProgressDialog progressDialog;

    // use a handler to update the UI (send the handler messages from other threads)
    private final Handler handler = new Handler() {

        @Override
        public void handleMessage(final Message msg) {
            progressDialog.dismiss();
            String bundleResult = msg.getData().getString("RESPONSE");
            output.setText(bundleResult);
        }
    };

    @Override
    public void onCreate(final Bundle icicle) {
        super.onCreate(icicle);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        // inflate the SAME view XML layout file as ApacheHTTPWithAuth Activity (re-use it)
        this.setContentView(R.layout.http_helper_form);

        this.param1Value = (EditText) findViewById(R.id.htth_param1_value);
        this.go = (Button) findViewById(R.id.htth_go_button);
        //this.output = (TextView) findViewById(R.id.htth_output);
        this.choices = (ListView) findViewById(R.id.list_of_choices);
        
        final String url = "http://teamsupercool.x10hosting.com/search.php";

        this.go.setOnClickListener(new OnClickListener() {

            public void onClick(final View v) {
                //output.setText("");
                result = getHttpResponse(url + "?c=search&keyword=" + param1Value.getText().toString());
                initListView();
            }
        });
    };
    
    private void refreshFavListItems() {
        choices.setAdapter(new ArrayAdapter<String>(this,
                  android.R.layout.simple_list_item_1, result));
   }
    
    private void initListView() {
        /* Loads the items to the ListView. */
        refreshFavListItems();

        choices.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent inte = new Intent(NutritionMe.this, Result.class);
				inte.putExtra("choice", choices.getAdapter().getItem(arg2).toString());
		        startActivity(inte);
			}
        	
		});
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, MAIN_ID, 0, R.string.menu_main);
        return result;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
        case MAIN_ID:
            startActivity(new Intent(NutritionMe.this, Main.class));
            return true;
        }
       
        return super.onOptionsItemSelected(item);
    }
    
    
    @Override
    public void onPause() {
        super.onPause();
        if ((this.progressDialog != null) && this.progressDialog.isShowing()) {
            this.progressDialog.dismiss();
        }
    }

    
    
    /**
     * Perform asynchronous HTTP using Apache <code>HttpClient</code> via
     * <code>HttpRequestHelper</code> and <code>ResponseHandler</code>.
     * 
     * @param url
     * @param method
     * @param param1Name
     * @param param1Value
     */
    private void performRequest(final String url, final String method, final String param1Name,
        final String param1Value) {

        Log.d(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " request url - " + url);
        Log.d(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " request method - " + method);
        Log.d(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " param1Name - " + param1Name);
        Log.d(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " param1Value - " + param1Value);
        
        final HashMap<String, String> params = new HashMap<String, String>();
        params.put("c","search");
        if ((param1Name != null) && (param1Value != null)) {
            params.put(param1Name, param1Value);
        }
        
        final ResponseHandler<String> responseHandler = HTTPRequestHelper.getResponseHandlerInstance(this.handler);

        this.progressDialog = ProgressDialog.show(this, "working . . .", "performing HTTP request");

        // do the HTTP dance in a separate thread (the responseHandler will fire when complete)
        new Thread() {

            @Override
            public void run() {
                HTTPRequestHelper helper = new HTTPRequestHelper(responseHandler);
                if (method.equals("GET")) {
                	String curl = url + "?c=search;keyword=potato";
                    helper.performGet(curl, null, null, null);
                } else if (method.equals("POST")) {
                    helper.performPost(HTTPRequestHelper.MIME_FORM_ENCODED, url, null, null, null, params);
                } else {
                    Message msg = handler.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putString("RESPONSE", "ERROR - see logcat");
                    msg.setData(bundle);
                    handler.sendMessage(msg);
                    Log.w(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " unknown method, nothing to do");
                }
            }
        }.start();
    }
    
    /**
     * Perform an HTTP GET with HttpUrlConnection.
     * 
     * @param location
     * @return
     */
    private ArrayList<String> getHttpResponse(String location) {
        String result = "";
        URL url = null;
        ArrayList<String> items = new ArrayList<String>();
        
        Log.d(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " location = " + location);

        try {
            url = new URL(location);
            Log.d(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " url = " + url);
        } catch (MalformedURLException e) {
            Log.e(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " " + e.getMessage());
        }

        if (url != null) {

           // this.progressDialog = ProgressDialog.show(this, "working . . .", "performing HTTP request");
        
        	
            try {
                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                String inputLine;

                //choices.setAdapter(new ListAdapter());

                while ((inputLine = in.readLine()) != null) {
                	if(!inputLine.equals("")){
                		Log.v(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " inputLine = " + inputLine);
                		result += "\n" + inputLine;
                		items.add(inputLine);
                	}
                }

                in.close();
                urlConn.disconnect();

            } catch (IOException e) {
                Log.e(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " " + e.getMessage());
            }

            //this.progressDialog.dismiss();
        } else {
            Log.e(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " url NULL");
        }
        return items;
    }
}
